/*
 * @Author: zhang ke
 * @Date: 2025-06-25 15:52:59
 * @LastEditors: your name
 * @LastEditTime: 2025-07-05 15:26:51
 * @Description: 
 * @FilePath: \vue3-admin\src\permission.ts
 */
import router from '@/router'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
//进度条去掉加载的样式
nprogress.configure({ showSpinner: false });
import useUserStore from './store/modules/user'
import pinia from './store'
import setting from './setting'
const userStore = useUserStore(pinia)
//全局前置守卫
router.beforeEach(async(to, form, next) => {
    document.title = to.meta.title + ` | ${setting.title}`
    // 进度条开始
    nprogress.start()
    // let token = userStore.token 
    let token =  userStore.token
    let username = userStore.username
    //用户登录了
    if (token || localStorage.getItem('TOKEN')) {
        if (to.path === '/login') {
            next({path:'/'})
        } else {
            // 有用户信息
            if(username){
                next()
            }else{
               try {
                await userStore.userInfo()
                    //没有用户信息先去拿用户信息
                    // 放行
          //        如果刷新的时候是异步路由，有可能获取到用户信息、异步路由还没有加载完毕，出险空白效果
                    next({...to})
               } catch (error) {
                    //token过期：获取不到用户信息
                    //用户手动修改本地存储的token
                    //退出登录----清除用户相关数据
                    await userStore.userLogout()
                    next({path:'/login',query:{redirect: to.path }})
               }
            }
            
        }

    } else {
        //用户未登录
        if (to.path === '/login') {
            next()
        } else {
            next({ path: '/login'})
        }
    }
})
//全局后置守卫
router.afterEach(() => {
    // 进度条结束
    nprogress.done()
})